package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.ChatItem;
import chaw.android.util.CustomCalendar;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChatRoomActivity extends ListActivity{
	final private int SEND_MESSAGE_FAIL = -1;
	final private int SEND_MESSAGE_SUCCESS = 0;
	private ArrayList<PeopleImage> ilist;
	private ArrayList<ChatItem> list;
	private ChatItemAdapter nadapter;
	private String roomId, latestCommentId;
	private ImageButton sendMessage;
	private Button btnBack, btnAddUser;
	private EditText editMessage;
	private TextView textTitle;
	private LocalBroadcastManager localBroadMgr;
	
	private Handler sendMessageToServerHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == SEND_MESSAGE_FAIL)
				Toast.makeText(getBaseContext(), "전송을 실패하였습니다.", Toast.LENGTH_SHORT).show();
			else if(msg.what == SEND_MESSAGE_SUCCESS)
				addComment(new ChatItem(Preferences.getValue(getBaseContext(), "user_name"), Preferences.getValue(getBaseContext(), "nick_name"), msg.getData().getString("message"), msg.getData().getString("when"), null, Preferences.getValue(getBaseContext(), "user_id")));
		}
	};
	
	private BroadcastReceiver chatRoomLocalcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle newBundle = intent.getExtras();
			String name = newBundle.getString("speaker");
			String message = newBundle.getString("message");
			String image_url = newBundle.getString("image_url");
			String user_id = newBundle.getString("user_id");
			long when = newBundle.getLong("when");
			String time = CustomCalendar.millisecondsToDate(when);
			ChatItem newComment = new ChatItem(name, name, message, time, image_url, user_id);
			addComment(newComment);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_room);
        
        sendMessage = (ImageButton) findViewById(R.id.sendMessage);
        btnBack = (Button) findViewById(R.id.btnBack);
        btnAddUser = (Button) findViewById(R.id.btnAddUser);
        editMessage = (EditText) findViewById(R.id.editMessage);
        textTitle = (TextView) findViewById(R.id.textTitle);
        
        sendMessage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!editMessage.getText().toString().equalsIgnoreCase("")){
					sendMessageToServer();
					InputMethodManager inputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
					inputManager.hideSoftInputFromWindow(editMessage.getWindowToken(), 0);
				}
			}
		});
        
        btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        
        btnAddUser.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(), CreateRoomActivity.class);
				intent.putExtra("roomId", getIntent().getExtras().getString("roomId"));
				intent.putExtra("isInvite", true);
				startActivity(intent);
			}
		});
	}
	
	private void sendMessageToServer(){
		final String message = editMessage.getText().toString();
		final String currentTime = CustomCalendar.getCurrentTime();
		final long when = CustomCalendar.calendar.getTimeInMillis();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					JSONObject chatData = new JSONObject();
					String shortMessage;
					if(message.length() > 400)
						shortMessage = message.substring(0, 400);
					else
						shortMessage = message;
					chatData.put("type", "chat");
					chatData.put("message", shortMessage);
					chatData.put("roomId", roomId);
					chatData.put("when", when);
					chatData.put("speaker", Preferences.getValue(getBaseContext(), "nick_name"));
					chatData.put("image_url", Preferences.getValue(getBaseContext(), "image_url"));
					chatData.put("user_id", Preferences.getValue(getBaseContext(), "user_id"));

					List<BasicNameValuePair> params  = new ArrayList<BasicNameValuePair>();
					params.add(new BasicNameValuePair("user_id", Preferences.getValue(getBaseContext(), "user_id")));
					params.add(new BasicNameValuePair("uuid_check", Preferences.getValue(getBaseContext(), "uuid")));
					params.add(new BasicNameValuePair("message", message));
					params.add(new BasicNameValuePair("data", chatData.toString()));
					params.add(new BasicNameValuePair("room_id", roomId));
					String result = HttpRequestManager.request(ServerURL.addComment, params);
					
					JSONObject resultData = new JSONObject(result);
					JSONObject commentData = resultData.getJSONObject("comment");
					latestCommentId = commentData.getString("comment_id");
					
					Message msg = new Message();
					if(result.equalsIgnoreCase("fail"))
						msg.what = SEND_MESSAGE_FAIL;
					else
						msg.what = SEND_MESSAGE_SUCCESS;
					Bundle data = new Bundle();
					data.putString("message", message);
					data.putString("when", currentTime);
					msg.setData(data);
					sendMessageToServerHandler.sendMessage(msg);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		
		editMessage.setText("");
	}
	
	private void addComment(ChatItem chatItem){
		nadapter = new ChatItemAdapter(this, R.layout.chat_row_other, R.id.talk, list);
		list.add(chatItem);
		ListView lv = getListView();
		lv.setAdapter(nadapter);
		lv.setSelection(list.size()-1);
	}
	
	private void setListView(){
		Intent currentIntent = getIntent();
		Bundle bundle = currentIntent.getExtras();
		
		list = new ArrayList<ChatItem>();
		ilist = new ArrayList<PeopleImage>();
		try{
			boolean isChat = bundle.getBoolean("isChat", false);
			if(isChat)
				roomId = bundle.getString("roomId");
			
			DownloadAsynkTask task = new DownloadAsynkTask();
			String[] params = new String[]{ ServerURL.commentList, "user_id", Preferences.getValue(getBaseContext(), "user_id"), 
					"user_id_check", Preferences.getValue(getBaseContext(), "user_id"), "room_id", roomId, "uuid_check", Preferences.getValue(getBaseContext(), "uuid") };
			task.execute(params);
		}catch (Exception e) {
			e.getStackTrace();
		}
	}

	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
	        DownloadAsynkTask2 task = new DownloadAsynkTask2();
	        task.execute(new String[]{result});
		}
	}

	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			try {
				JSONObject chat = new JSONObject(urls[0]);
				JSONObject commentData = chat.getJSONObject("comment");
				JSONArray usersInRoom = chat.getJSONArray("user_list");
				JSONArray chatContents = commentData.getJSONArray("comments");
				
				latestCommentId = "0";
				for(int i=0; i<chatContents.length(); i++){
					JSONObject eachChat = chatContents.getJSONObject(i);
					ChatItem eachItem = new ChatItem(eachChat.getString("nick_name"), eachChat.getString("nick_name"), eachChat.getString("message"),
							CustomCalendar.parseTime(eachChat.getString("date")), eachChat.getString("image_url"), eachChat.getString("user_id"));
			        list.add(eachItem);
			        
			        String comment_id = eachChat.getString("comment_id");
			        if(Integer.valueOf(comment_id) > Integer.valueOf(latestCommentId) )
			        	latestCommentId = comment_id;
				}
				
				for(int i = 0 ; i < usersInRoom.length(); i++){
					JSONObject eachUser = usersInRoom.getJSONObject(i);
					Bitmap image = null;
					if(!eachUser.get("image_url").toString().equals("") && eachUser.get("image_url") != null){
						image = LoadBitMap.fromURL(eachUser.get("image_url").toString());
					}
					PeopleImage people = new PeopleImage(eachUser.get("nick_name").toString(), image);
					ilist.add(people);
				}
				JSONObject someUser = usersInRoom.getJSONObject(0);
				if(someUser.getString("user_id").equalsIgnoreCase(Preferences.getValue(getBaseContext(), "user_id")))
					someUser = usersInRoom.getJSONObject(1);
				
				String speakers;
				if(usersInRoom.length() > 2)
					speakers = someUser.getString("nick_name") + "님 외 " + ( usersInRoom.length() - 2) + "명";
				else
					speakers = someUser.getString("nick_name") + "님";
				response = speakers;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			textTitle.setText(result);
			nadapter = new ChatItemAdapter(getBaseContext(), R.layout.chat_row_other, R.id.talk, list);
			ListView lv = getListView();
			lv.setAdapter(nadapter);
			lv.setSelection(list.size()-1);
		}
	}
	private class PeopleImage{
		private String user_name;
		private Bitmap user_image;
		public PeopleImage(String name, Bitmap image){
			user_name = name;
			user_image = image;
		}
		
		public String getName(){
			return user_name;
		}
		public Bitmap getImage(){
			return user_image;
		}
		
	}

	private class ChatItemAdapter extends ArrayAdapter<ChatItem>{
		private ArrayList<ChatItem> items;
		private int rsrc;
		
		public ChatItemAdapter(Context ctx, int rsrcId, int txtId, ArrayList<ChatItem> data){
			super(ctx, rsrcId, txtId, data);
			this.items = data;
			this.rsrc = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			final ChatItem e = items.get(position);
			if(Preferences.getValue(getBaseContext(), "nick_name").equalsIgnoreCase(e.getNickName())){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.chat_row_me, null);
				((TextView)v.findViewById(R.id.talk)).setText(e.getUserMessage());
				((TextView)v.findViewById(R.id.sendTime)).setText(e.getSendTime());
			}
			else{
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
				if(e != null){
					((TextView)v.findViewById(R.id.userName)).setText(e.getNickName());
					((TextView)v.findViewById(R.id.talk)).setText(e.getUserMessage());
					((TextView)v.findViewById(R.id.sendTime)).setText(e.getSendTime());
					((TextView)v.findViewById(R.id.userName)).setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							Intent intent = new Intent(getBaseContext(), TrainTravelActivity.class);
							intent.putExtra("user_id", e.getUser_id());
							intent.setFlags(FavoriteActivity.PROFILE_VIEW);
							startActivity(intent);
						}
					});
					for(int i = 0 ; i < ilist.size() ; i++){
						PeopleImage people = ilist.get(i);
						if(e.getNickName().equals(people.getName())){
							if(people.getImage() != null){
								((ImageView)v.findViewById(R.id.icon)).setImageBitmap(people.getImage());
							}
							else{
								((ImageView)v.findViewById(R.id.icon)).setImageResource(R.drawable.icon_noprofile_m);
							}
						}
					}
				}
			}
			return v;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		setListView();
		setLocalCastReceiver();
		isNotification();
		
		if(Preferences.getBoolean(getBaseContext(), "configFixDisplay")){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
	}
	
	private void isNotification(){
		NotificationManager nm = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
		nm.cancel(Integer.parseInt(getIntent().getExtras().getString("roomId")));
	}
	
	private void setLocalCastReceiver(){
		localBroadMgr = LocalBroadcastManager.getInstance(getBaseContext());
        IntentFilter filter = new IntentFilter(roomId);
        filter.addCategory("chatRoom");
        localBroadMgr.registerReceiver(chatRoomLocalcastReceiver, filter);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return false;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		localBroadMgr.unregisterReceiver(chatRoomLocalcastReceiver);
	}
}
